from common.response import Response
from constants.header_constant import LCQuestionHeaderConstant
from dao.leetcode_question_dao import LeetCodeQuestionDao
from models.leetcode_question_model import LeetCodeQuestionModel
from schemas.leetcode_question_schema import LeetCodeQuestionSchema, DeleteQuestionSchema, \
    UpdateQuestionSchema


class LeetCodeQuestionService:
    def __init__(self):
        self.question_dao = LeetCodeQuestionDao()

    async def create_question(self, params: LeetCodeQuestionSchema) -> Response:
        exists = await self.question_dao.get_by_query({'lc_sn': params.lc_sn})
        if exists:
            return Response.fail(f'相同序号的题目已存在')
        await self.question_dao.insert_one(LeetCodeQuestionModel(**params.dict()))
        return Response.success()

    async def list_question(self) -> Response:
        questions = await self.question_dao.get_by_query_params({})
        header = LCQuestionHeaderConstant.question_header
        res = {
            'header': header,
            'data': questions
        }
        return Response.success(res)

    async def update_question(self, params: UpdateQuestionSchema) -> Response:
        question = await self.question_dao.get_one_by_query({'_id': params.id})
        if not question:
            return Response.fail(f'该题目不存在')
        update_data = params.dict(exclude={'id'})
        await self.question_dao.update_by_id(question.id, update_data)
        return Response.success()

    async def delete_question(self, params: DeleteQuestionSchema) -> Response:
        await self.question_dao.delete_by_id(params.id)
        return Response.success()
